{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 6.1\t基本存储：存储至txt或csv"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 6.1.1把数据存储至txt"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-11-18T14:30:19.089018Z",
     "start_time": "2018-11-18T14:30:19.086009Z"
    }
   },
   "outputs": [],
   "source": [
    "title = \"This is a test sentence.\"\n",
    "with open(r'C:\\Users\\santostang\\Desktop\\title.txt', \"a+\") as f:\n",
    "    f.write(title)\n",
    "    f.close()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-11-18T14:30:19.751164Z",
     "start_time": "2018-11-18T14:30:19.747656Z"
    }
   },
   "outputs": [],
   "source": [
    "output = '\\t'.join(['name','title','age','gender'])\n",
    "with open('C:\\\\Users\\\\santostang\\\\desktop\\\\test.txt', \"a+\") as f:\n",
    "    f.write(output)\n",
    "    f.close()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-11-18T14:30:38.210437Z",
     "start_time": "2018-11-18T14:30:38.198405Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "This is a test sentence.\n"
     ]
    }
   ],
   "source": [
    "with open(r'C:\\Users\\santostang\\Desktop\\title.txt', \"r\", encoding ='utf-8') as f:\n",
    "    result = f.read()\n",
    "    print (result)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-11-18T14:32:10.779825Z",
     "start_time": "2018-11-18T14:32:10.776817Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['This is a test sentence.', 'This is the second test sentence.', 'This is the third test sentence.']\n"
     ]
    }
   ],
   "source": [
    "with open(r'C:\\Users\\santostang\\Desktop\\title.txt', \"r\", encoding ='utf-8') as f:\n",
    "    result = f.read().splitlines()\n",
    "    print (result)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 6.1.2把数据存储至csv"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-11-18T14:43:09.018560Z",
     "start_time": "2018-11-18T14:43:09.014551Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['\\ufeffA1', 'B1', 'C1', 'D1']\n",
      "﻿A1\n",
      "['A2', 'B2', 'C2', 'D2']\n",
      "A2\n",
      "['A3', 'B3', 'C3', 'D3']\n",
      "A3\n",
      "['A4', 'B4', 'C4', 'D4']\n",
      "A4\n"
     ]
    }
   ],
   "source": [
    "import csv\n",
    "with open('test.csv', 'r',encoding='utf-8') as csvfile:\n",
    "    csv_reader = csv.reader(csvfile)\n",
    "    for row in csv_reader:\n",
    "        print(row)\n",
    "        print(row[0])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-11-18T14:43:35.680232Z",
     "start_time": "2018-11-18T14:43:35.676723Z"
    }
   },
   "outputs": [],
   "source": [
    "import csv\n",
    "output_list = ['1', '2','3','4']\n",
    "with open('test2.csv', 'a+', encoding='utf-8', newline='') as csvfile:\n",
    "    w = csv.writer(csvfile)\n",
    "    w.writerow(output_list)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 6.2 储存至MySQL数据库"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 6.2.3 Python操作MySQL数据库"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-11-25T15:24:14.804439Z",
     "start_time": "2018-11-25T15:24:14.764978Z"
    }
   },
   "outputs": [],
   "source": [
    "import pymysql\n",
    " \n",
    "# 打开数据库连接\n",
    "db = pymysql.connect(\"localhost\",\"root\",\"password\",\"scraping\" )\n",
    " \n",
    "# 使用cursor()方法获取操作游标 \n",
    "cursor = db.cursor()\n",
    " \n",
    "# SQL 插入语句\n",
    "sql = \"\"\"INSERT INTO urls (url, content) VALUES ('www.baidu.com', 'This is content.')\"\"\"\n",
    "try:\n",
    "   # 执行sql语句\n",
    "   cursor.execute(sql)\n",
    "   # 提交到数据库执行\n",
    "   db.commit()\n",
    "except:\n",
    "   # 如果发生错误则回滚\n",
    "   db.rollback()\n",
    "# 关闭数据库连接\n",
    "db.close()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-11-28T15:14:41.464834Z",
     "start_time": "2018-11-28T15:14:40.915500Z"
    }
   },
   "outputs": [],
   "source": [
    "import requests\n",
    "from bs4 import BeautifulSoup\n",
    "import pymysql\n",
    "\n",
    "db = pymysql.connect(\"localhost\",\"root\",\"password\",\"scraping\" )\n",
    "cursor = db.cursor()\n",
    "\n",
    "link = \"http://www.santostang.com/\"\n",
    "headers = {'User-Agent' : 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.6) Gecko/20091201 Firefox/3.5.6'}\n",
    "r = requests.get(link, headers= headers)\n",
    "\n",
    "soup = BeautifulSoup(r.text, \"lxml\")\n",
    "title_list = soup.find_all(\"h1\", class_=\"post-title\")\n",
    "for eachone in title_list:\n",
    "    url = eachone.a['href']\n",
    "    title = eachone.a.text.strip()\n",
    "    cursor.execute(\"INSERT INTO urls (url, content) VALUES (%s, %s)\", (url, title))\n",
    "    \n",
    "db.commit()\n",
    "db.close()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 6.3 储存至MongoDB数据库"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 6.3.3 Python操作MongoDB数据库"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-11-28T16:22:17.163745Z",
     "start_time": "2018-11-28T16:22:17.046880Z"
    }
   },
   "outputs": [],
   "source": [
    "from pymongo import MongoClient\n",
    "client = MongoClient('localhost',27017)\n",
    "db = client.blog_database\n",
    "collection = db.blog"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-11-28T16:23:15.311100Z",
     "start_time": "2018-11-28T16:23:15.018597Z"
    }
   },
   "outputs": [],
   "source": [
    "import requests\n",
    "import datetime\n",
    "from bs4 import BeautifulSoup\n",
    "from pymongo import MongoClient\n",
    "\n",
    "client = MongoClient('localhost',27017)\n",
    "db = client.blog_database\n",
    "collection = db.blog\n",
    "\n",
    "link = \"http://www.santostang.com/\"\n",
    "headers = {'User-Agent' : 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.6) Gecko/20091201 Firefox/3.5.6'} \n",
    "r = requests.get(link, headers= headers)\n",
    "\n",
    "soup = BeautifulSoup(r.text, \"lxml\")\n",
    "title_list = soup.find_all(\"h1\", class_=\"post-title\")\n",
    "for eachone in title_list:\n",
    "    url = eachone.a['href']\n",
    "    title = eachone.a.text.strip()\n",
    "    post = {\"url\": url,\n",
    "         \"title\": title,\n",
    "         \"date\": datetime.datetime.utcnow()}\n",
    "    collection.insert_one(post)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.5"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
